package com.taoyibao.hongcanting.ui.webview;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityNoSlidePresenter;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.h5.MyWebViewClient;
import com.taoyibao.hongcanting.widget.ErrorView;

/**
 * @author TangAnna
 * @description: 简单的WebView展示页面使用
 * @date :${DATA} 18:14
 */
public class CommonWebViewActivity extends BaseActivityNoSlidePresenter<CommonWebViewDelegate> implements ErrorView.OnErrorListener {

    private WebView mWebView;
    private String mTitle;
    private String mUrl;
    private ErrorView mErrorView;

    @Override
    protected Class<CommonWebViewDelegate> getDelegateClass() {
        return CommonWebViewDelegate.class;
    }

    /**
     * @param context
     * @param title   页面title
     * @param url     webView 地址
     */
    public static void open(Context context, String title, String url) {
        Intent intent = new Intent(context, CommonWebViewActivity.class);
        intent.putExtra(CodeConstant.TITLE, title);
        intent.putExtra(CodeConstant.WEBVIEW_URL, url);
        context.startActivity(intent);
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        mTitle = getIntent().getStringExtra(CodeConstant.TITLE);
        mUrl = getIntent().getStringExtra(CodeConstant.WEBVIEW_URL);
        if (!TextUtils.isEmpty(mTitle)) {
            viewDelegate.setTitle(mTitle);
        }

        mErrorView = viewDelegate.get(R.id.errorView);
        mErrorView.setOnErrorListener(this);
        mWebView = viewDelegate.get(R.id.webView);
        //设置WebView的参数
        WebSettings settings = mWebView.getSettings();
        //设置两端可以交互
        settings.setJavaScriptEnabled(true);
        //设置WebView根据手机去适配
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);//打开DOM存储API
        //设置WebView不使用缓存
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        //加载地址
        if (!TextUtils.isEmpty(mUrl)) {
            mWebView.loadUrl(mUrl);
        }
        mWebView.setWebViewClient(new MyWebViewClient(this, mErrorView));
    }

    @Override
    public void errorListener() {
        mWebView.reload();
    }
}
